package com.ilxqx.framework.config;

import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Jackson配置类
 * @author venus
 */
@Configuration
public class JacksonConfig {

	/**
	 * 日期格式
	 */
	@Value("${spring.jackson.date-format}")
	private String datePattern;

	/**
	 * 日期时间格式
	 */
	@Value("${spring.jackson.joda-date-time-format}")
	private String datetimePattern;

	/**
	 * 重置日期时间序列化
	 * @return serializer
	 */
	private LocalDateTimeSerializer localDateTimeSerializer() {
		return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(this.datetimePattern));
	}

	/**
	 * 重置日期序列化
	 * @return serializer
	 */
	private LocalDateSerializer localDateSerializer() {
		return new LocalDateSerializer(DateTimeFormatter.ofPattern(this.datePattern));
	}

	/**
	 * jackson配置
	 * @return 自定义配置
	 */
	@Bean
	public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
		return jacksonObjectMapperBuilder -> {
			jacksonObjectMapperBuilder
				.serializerByType(LocalDateTime.class, this.localDateTimeSerializer())
				.serializerByType(LocalDate.class, this.localDateSerializer());
		};
	}

}
